package kmeans;

import org.apache.hadoop.io.Writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public class Cluster implements Writable {
    private int clusterId;
    private long pointsNumber;
    private Instance center;

    public Cluster() {
        this.setClusterId(-1);
        this.setPointsNumber(0);
        this.setCenter(new Instance());
    }

    public Cluster(int clusterId, Instance center) {
        this.setClusterId(clusterId);
        this.setPointsNumber(1);
        this.setCenter(center);
    }

    public Cluster(String line) {
        String[] values = line.split(",", 3);
        this.setClusterId(Integer.parseInt(values[0]));
        this.setPointsNumber(Long.parseLong(values[1]));
        this.center = new Instance(values[2]);
    }

    public int getClusterId() {
        return clusterId;
    }

    public long getPointsNumber() {
        return pointsNumber;
    }

    public Instance getCenter() {
        return center;
    }

    public void setClusterId(int clusterId) {
        this.clusterId = clusterId;
    }

    public void setCenter(Instance center) {
        this.center = center;
    }

    public void setPointsNumber(long pointsNumber) {
        this.pointsNumber = pointsNumber;
    }

    public double ComputeDist(Instance instance) {
        return center.ComputeDist(instance);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Cluster) {
            Cluster cluster = (Cluster) obj;
            return (cluster.getClusterId() == getClusterId() &&
                    cluster.getPointsNumber() == getPointsNumber() &&
                    cluster.getCenter().equals(getCenter()));
        }
        return false;
    }

    @Override
    public String toString() {
        return clusterId + "," + pointsNumber + "," + center.toString();
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeInt(clusterId);
        dataOutput.writeLong(pointsNumber);
        center.write(dataOutput);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        clusterId = dataInput.readInt();
        pointsNumber = dataInput.readLong();
        center.readFields(dataInput);
    }
}
